import React from 'react';
import { observer, inject } from 'mobx-react';
import { TabPage, RouteLayout, BrowserHrm } from 'weaver-mobile-page'
import { Route, withRouter, Switch, Redirect } from 'react-router-dom';
import { Popover, Icon, Tools } from 'weaver-mobile';
import Detail from '../detail/index'
import Search from '../search/index'
import CalendarAndList from './calendarAndList'
import moment from 'moment';
const getLabel = Tools.getLabel;
const Item = Popover.Item;
const mobileDetect = Tools.mobileDetect()
@inject('viewMeetingStore')
@inject('meetingSearchStore')
@inject('calendarStore')
@withRouter
@observer
export default class MeetingCalendar extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      nowTab: 0,
      visible: false,
      overlay: [
        (<Item key={0} data-seed="logId">{getLabel(391082, '按指定人员查看')}</Item>),
      ],
    };
  }

  componentWillMount() {
    let is_mobi = mobileDetect.mobile()
    if (is_mobi && window.em && window.em.checkJsApi('scanQRCode')) {
      this.setState({
        overlay: [
          ...this.state.overlay,
          (<Item className='item1' key={1} >{getLabel(34234, '扫一扫')}</Item>),
        ]
      })
    } else {

    }
    //作用是首次进入calendar的时候将选择的selectUser从sessionStorage中移除
    const pathName = this.props.history.location.pathname;
    if (pathName === '/calendar') {
      sessionStorage.removeItem('meetingSelectUserId')
    }
    if (!sessionStorage.meetingTitle) {
      sessionStorage.setItem('meetingTitle', getLabel(32483, '会议日历'))

    }
    if (window.em && this.props.history.action === 'POP') {
      window.em.checkJsApi('changeTitle') && window.em.changeTitle({ title: sessionStorage.meetingTitle ? sessionStorage.meetingTitle : getLabel(32483, '会议日历') })
    } else {
      window.em && window.em.checkJsApi('changeTitle') && window.em.changeTitle({ title: getLabel(32483, '会议日历') })
    }

  }

  componentDidMount() {
    //只有第一次进入的时候才会走didmount,在初次进入的时候默认显示当天,不用管sessionStorage中的信息
    // if(sessionStorage && !sessionStorage.meetingSelectdate){
    sessionStorage.setItem('meetingSelectdate', moment(new Date()).format("YYYY-MM-DD"))
    // }

    //根据sessionStorage中是否存在meetingNowTab,判断跳转tab页面以及meetingType
    //因为meetingType是根据tab.key来决定的,所以两者是同一个值
    if (sessionStorage && sessionStorage.meetingNowTab) {
      this.setState({ nowTab: parseInt(sessionStorage.meetingNowTab, 10) })
    }
  }

  componentWillReceiveProps(nextProps) {
    const prePath = this.props.location.pathname;
    const curPath = nextProps.location.pathname;
    if (curPath && curPath !== prePath) {
      if (curPath.indexOf('detail') < 0) {
        this.setPage(curPath);
        let isUser = sessionStorage.getItem('meetingSelectUserId')
        if (isUser) {
          let title = sessionStorage.getItem('meetingTitle')
          window.em && window.em.checkJsApi('changeTitle') && window.em.changeTitle({ title: title })
        } else {
          window.em && window.em.checkJsApi('changeTitle') && window.em.changeTitle({ title: getLabel(32483, '会议日历') })
        }
      }
    }
  }

  componentWillUpdate(preProps) {
    const { location: { pathname: preP }, history: h } = preProps;
    const { location: { pathname: p } } = this.props;
    const reg = /\/[^\\/]+$/;
    if (preP !== p && preP.replace(reg, '') === p.replace(reg, '') && h.action === 'POP') {
      if (window.em) {
        if (p.indexOf('detail') < 0 && p.indexOf('search') < 0) {
          sessionStorage.removeItem('meetingSelectdate');
          sessionStorage.removeItem('meetingNowTab');
          sessionStorage.removeItem('meetingId');
          //因为微信企业好不支持openLink,所以在打开工作台后closeWindow是连同工作台一起关闭的
          window.em.checkJsApi('openLink') && window.em.checkJsApi('closeWindow') && window.em.closeWindow();
          !window.em.checkJsApi('openLink') && h.go(-1);
          return false;
        }
      }
    } else {
      return true;
    }
  }

  componentWillUnmount() {
    sessionStorage.removeItem('meetingSelectdate');
    sessionStorage.removeItem('meetingNowTab');
    sessionStorage.removeItem('meetingId');
  }

  getCalendarInfo(params) {
    const { getCalendarInfo, meetingType } = this.props.calendarStore;
    getCalendarInfo({ ismobile: 1, viewType: '3', isCalendar: '1', meetingType: meetingType, ...params });
  }

  getCalendarList(params) {
    const { getCalendarInfo, meetingType } = this.props.calendarStore;
    getCalendarInfo({ ismobile: 1, viewType: '1', isCalendar: '0', meetingType: meetingType, ...params });
  }


  showSearchCondition() {
    const { history } = this.props;
    // const { search,getConditon } = meetingSearchStore;
    // getConditon(search);
    history.push("/calendar/search");
  }

  setPage = (path) => {
    const { setHrmBrowserRoute, calendarTabPath } = this.props.calendarStore;
    if (path.indexOf(calendarTabPath[0]) > -1) { this.setState({ nowTab: 0 }); sessionStorage.setItem("meetingNowTab", 0); setHrmBrowserRoute(calendarTabPath[0]); }
    if (path.indexOf(calendarTabPath[1]) > -1) { this.setState({ nowTab: 1 }); sessionStorage.setItem("meetingNowTab", 1); setHrmBrowserRoute(calendarTabPath[1]); }
    if (path.indexOf(calendarTabPath[2]) > -1) { this.setState({ nowTab: 2 }); sessionStorage.setItem("meetingNowTab", 2); setHrmBrowserRoute(calendarTabPath[2]); }
    if (path.indexOf(calendarTabPath[3]) > -1) { this.setState({ nowTab: 3 }); sessionStorage.setItem("meetingNowTab", 3); setHrmBrowserRoute(calendarTabPath[3]); }
  }


  // 点击tab页切换
  changeTab = (tab, index) => {
    const { setHrmBrowserRoute, calendarTabPath } = this.props.calendarStore;
    sessionStorage.setItem("meetingNowTab", tab.key);
    switch (tab.key) {
      case 0: this.setPath(index, calendarTabPath[0]); setHrmBrowserRoute(calendarTabPath[0]); break;
      case 1: this.setPath(index, calendarTabPath[1]); setHrmBrowserRoute(calendarTabPath[1]); break;
      case 2: this.setPath(index, calendarTabPath[2]); setHrmBrowserRoute(calendarTabPath[2]); break;
      case 3: this.setPath(index, calendarTabPath[3]); setHrmBrowserRoute(calendarTabPath[3]); break;
      default: return;
    }
  }

  setPath = (key, path) => {
    this.props.history.push(path);
  }

  handleSelect = (opt) => {
    const { calendarStore } = this.props;
    const { hrmBrowser } = calendarStore;
    this.setState({
      visible: false,
    });
    if (opt.key === '0') {
      this.props.history.push(hrmBrowser.path)
    } else if (opt.key === '1') {
      this.scan()
    }
  }

  handleVisibleChange = (visible) => {
    this.setState({
      visible,
    });
  };

  openUserCalendar = (user) => {
    sessionStorage.setItem('meetingSelectUserId', user[0]);
    sessionStorage.setItem('meetingTitle', `${user[1]}${getLabel(387622, '的会议')}`)
    const { hrmBrowser, selectUserId, setState } = this.props.calendarStore;
    setState({
      selectUserId: user[0],
    });
    if (window.em) {
      if (user[0]) {
        window.em.checkJsApi('changeTitle') && window.em.changeTitle({ title: `${user[1]}${getLabel(387622, '的会议')}` })
      } else {
        //浏览按钮清除的时候user[0]为空
        window.em.checkJsApi('changeTitle') && window.em.changeTitle({ title: `${user[1]}${getLabel(32483, '会议日历')}` })
      }
    }
  }

  openRoomPlan = () => {
    const { selectdate } = this.props.calendarStore;
    const pathName = this.props.history.location.pathname;
    this.props.history.push({ pathname: `${pathName}/report`, query: { selectDate: selectdate } });
  }

  scan = () => {
    const em = window.em
    let isEmobile = mobileDetect.isEmobile()
    let origin = window.location.origin
    let protocol = window.location.protocol
    let isHttpStart = (protocol == 'https:' || protocol == 'http:') ? true : false;
    if (em) {
      em.ready(() => {
        if (em.checkJsApi('scanQRCode')) {
          em.scanQRCode({
            scanType: ['qrCode'],
            success: function (res) {
              let isSpa = res.resultStr.indexOf('/spa') > -1 ? true : false;
              if (!isEmobile && isSpa && isHttpStart) {
                window.open(origin + res.resultStr)
              }
            },
            fail: function (res) {
            }
          })
        }
      });
    } else {
      alert('error', 'err:-900')
    }
  }

  getHrmBrowser = () => {
    const { hrmBrowserTabs } = this.props.calendarStore;
    const { pathname } = this.props.history.location;
    let store = hrmBrowserTabs.allMeeting;
    if(pathname.indexOf('allMeeting') > -1) {
      store = hrmBrowserTabs.allMeeting;
    }
    if(pathname.indexOf('endMeeting') > -1) {
      store = hrmBrowserTabs.endMeeting;
    }
    if(pathname.indexOf('goingMeeting') > -1) {
      store = hrmBrowserTabs.goingMeeting;
    }
    if(pathname.indexOf('notStartMeeting') > -1) {
      store = hrmBrowserTabs.notStartMeeting;
    }
    return store;
  }

  render() {
    const { calendarStore } = this.props;
    const { hrmBrowser, selectUserId, hrmBrowserLoading } = calendarStore;
    const { overlay, visible } = this.state;
    const tabs = [
      { title: getLabel(131378, "全部"), key: 0 },
      { title: getLabel(383417, "已结束"), key: 1 },
      { title: getLabel(1960, "进行中"), key: 2 },
      { title: getLabel(383418, "未开始"), key: 3 }
    ];
    const btns = [
      <Icon type="filter-o" onClick={this.showSearchCondition.bind(this)} />,
    ];

    const { span } = this.state;

    const tabProps = {
      onChange: (tab, index) => { this.changeTab(tab, index) },
      page: this.state.nowTab
    };

    const popoverProps = {
      visible,
      overlay,
      onSelect: this.handleSelect,
      onVisibleChange: this.handleVisibleChange,
    };
    return (
      <div style={{ overflow: 'hidden', height: document.body.clientHeight - 55 }} >
        <div style={{ height: '0px' }} >
          <BrowserHrm
            label={getLabel(391082, '按指定人员查看')}
            store={this.getHrmBrowser()}
            type={17}
            isSingle={true}
            onChange={(...arg) => { this.openUserCalendar(arg) }}
          >
          </BrowserHrm>
        </div>
        <TabPage
          btns={btns}
          span={span}
          tabs={tabs}
          tabProps={tabProps}
          popover={true}
          popoverProps={popoverProps}
        />
        <div className="tab-page" style={{ height: '100%' }}>
          <Switch>
            <Route
              key="allMeeting"
              path="/calendar/allMeeting"
              render={() => <CalendarAndList calendarStore={calendarStore} selectUser={selectUserId} />}
            />
            <Route
              key="endMeeting"
              path="/calendar/endMeeting"
              render={() => <CalendarAndList calendarStore={calendarStore} selectUser={selectUserId} />}
            />
            <Route
              key="goingMeeting"
              path="/calendar/goingMeeting"
              render={() => <CalendarAndList calendarStore={calendarStore} selectUser={selectUserId} />}
            />
            <Route
              key="notStartMeeting"
              path="/calendar/notStartMeeting"
              render={() => <CalendarAndList calendarStore={calendarStore} selectUser={selectUserId} />}
            />
            <Route
              key="meetingDetail"
              path="/calendar/detail"
              render={() => (
                <RouteLayout>
                  <div key="calendarDetailDiv" className="wm-route-layout wm-demo-route-layout-page">
                    <Detail />
                  </div>
                </RouteLayout>
              )}
            />
            <Route
              key="search"
              path="/calendar/search"
              render={() => (
                <RouteLayout>
                  <div key="searchDetailDiv" className="wm-route-layout wm-demo-route-layout-page">
                    <Search />
                  </div>
                </RouteLayout>
              )}
            />
            <Redirect exact path="/calendar" to={{ pathname: '/calendar/allMeeting' }} />
          </Switch>

          {/* {this.getFooter()} */}

        </div>
      </div>
    );
  }
}